<template>
  <div class="v-upload">
    <el-upload :key="key" action="#" :http-request="httpRequest" :show-file-list="false" v-bind="$attrs"
      :class="props.classes">
      <slot />
    </el-upload>
    <el-progress v-if="props.progress && progressPercent" :percentage="progressPercent" :width="128" />
  </div>
</template>

<script setup>
import { uploadImg, uploadFile } from './api'
import axios from 'axios'
// import MD5 from 'spark-md5'
const props = defineProps({
  type: { type: String, default: 'img' }, // 上传类型
  limit: { type: Number, default: 1 },
  classes: { type: String, default: '' }, // el-upload的class
  validator: { type: Function, default: () => { } }, // 校验函数
  progress: Boolean // 是否使用进度条
})
const emit = defineEmits(['success', 'error'])
const key = ref(0)
const progressPercent = ref(0)
watch(progressPercent, (val) => {
  if (val === 100) {
    const timer = setTimeout(() => {
      progressPercent.value = 0
      clearTimeout(timer)
    }, 1000)
  }
})
const beforeUpload = (file) => {
  if (props.limit === 1) key.value++
  return new Promise((resolve, reject) => {
    const { name, type, size } = file
    const url = URL.createObjectURL(file)
    const types = {
      // 图片上传
      img: () => {
        let img = document.createElement('img')
        img.src = url
        img.onload = () => {
          const { width, height } = img
          const fileInfo = { width, height, size, name, type }
          // 校验
          const massge = props.validator && props.validator(fileInfo)
          img = null
          massge && reject(massge)
          resolve(fileInfo)
        }
      },
      // 视频上传
      video: () => {
        let video = document.createElement('video')
        video.preload = 'metadata'
        video.src = url
        video.autoplay = true
        video.onloadedmetadata = () => {
          const { duration, videoWidth: width, videoHeight: height } = video
          const fileInfo = { width, height, size, name, type, time: Math.ceil(duration) }
          // 校验
          const massge = props.validator && props.validator(fileInfo)
          video = null
          massge && reject(massge)
          resolve(fileInfo)
        }
      },
      // 文件上传
      file: () => {
        resolve()
      }
    }
    types[props.type]()
  })
}
const httpRequest = (fileData) => {
  const { file } = fileData
  beforeUpload(file).then(fileInfo => {
    progressPercent.value = 0
    let formData = new FormData();
    formData.append('file', file)
    const requestFunction = props.type === 'img' ? uploadImg : uploadFile
    requestFunction(formData).then(res => {
      // const spark = new MD5.ArrayBuffer()
      // spark.append(file)
      // const secret = spark.end(false)
      emit('success', { ...fileInfo, ...res.data })
    })
  }).catch(e => {
    console.log(e);
    emit('error', e)
  })
}
</script>

<style lang="scss" scoped></style>